package com.xingdian.xingdianhulianserver.util.ossUtil.util;

import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@Component
public class DownFileServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        // request通过getParameter得到filename这个参数的值
        String filename = request.getParameter("filename");
        System.out.println(filename);
        // response设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename="+filename);
        String path = null;
        // jpg和mp3都存在于web应用目录下，mp4则存在于F盘的movie文件夹下
        // 如果是jpg或者mp3则通过它们的相对路径得到绝对路径
        if(filename.endsWith("jpg")){
            path= this.getServletContext().getRealPath("/images/"+filename);
        }else if (filename.endsWith("mp3")){
            path= this.getServletContext().getRealPath("/musics/"+filename);
        }else if(filename.endsWith("mp4")){
            path = "F:\\movie\\"+filename;
        }
        FileInputStream fis = new FileInputStream(path);
        byte buff[] = new byte[2048];
        int len = 0;
        OutputStream os = response.getOutputStream();
        while((len = fis.read(buff))>0){
            os.write(buff, 0, len);
        }
        os.close();
        fis.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doGet(request, response);
    }

}
